package com.codeduck.async.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 测试同步异步任务
 *
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2021-12-26
 */
@Component
@Slf4j
public class TaskFactory {

    /**
     * 处理异步回调：如果异步方法具有返回值的话，需要使用Future来接收回调值。
     * 模拟5秒的异步任务
     */
    @Async
    public Future<Boolean> asyncTask1() throws InterruptedException {
        doTask("asyncTask1", 5);
        return new AsyncResult<>(Boolean.TRUE);
    }

    /**
     * 模拟2秒的异步任务
     */
    @Async
    public Future<Boolean> asyncTask2() throws InterruptedException {
        doTask("asyncTask2", 2);
        return new AsyncResult<>(Boolean.TRUE);
    }


    /**
     * 模拟5秒的同步任务
     */
    public void syncTask1() throws InterruptedException {
        doTask("syncTask1", 5);
    }

    /**
     * 模拟2秒的同步任务
     */
    public void syncTask2() throws InterruptedException {
        doTask("syncTask2", 2);
    }

    private void doTask(String taskName, Integer time) throws InterruptedException {
        log.info("{} 开始执行，当前线程名称[{}]", taskName, Thread.currentThread().getName());
        log.info("[{}] 线程执行任务需要耗时：{} s", Thread.currentThread().getName(), time);
        TimeUnit.SECONDS.sleep(time);
        log.info("{} 执行完毕，当前线程名称[{}]", taskName, Thread.currentThread().getName());
    }
}
